<?php 
namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Jobs\SaveUserAvatar;
use App\User;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Facades\JWTAuth;
use Illuminate\Support\Facades\Validator;

class AuthController extends Controller
{
	const API_OAUTH_GET = 'https://api.weixin.qq.com/sns/userinfo';

    public function wechat(Request $request)
    {
        $input = $request->only('access_token', 'openid');
        $input['lang'] = 'zh_CN';

        $client = new Client;
        $response = $client->request('GET', self::API_OAUTH_GET, ['query' => $input]);

        $body = $response->getBody();
        $data = json_decode($body, true);

        if (array_key_exists('errcode', $data)) {
            return response()->json(['code' => 9000, 'msg' => $data['errmsg']]);
        } else {
            $openid = $data['openid'];
            $unionid = $data['unionid'];

            if ($user = User::where('openid_app', $openid)->first()) {
            } elseif ($user = User::where('unionid', $unionid)->first()) {
                $user->openid_app = $openid;
                $user->save();

                $user->update(['status' => DB::raw('status|1')]);
            } else {
                $user = new User;
                $user->openid = '';
                $user->openid_app = $openid;
                $user->unionid = $unionid;
                $user->avatar = $data['headimgurl'];
                $user->nickname = $data['nickname'];
                $user->sex = $data['sex'];
                $user->country = $data['country'];
                $user->province = $data['province'];
                $user->city = $data['city'];
                $user->password = '';
                $user->status = 1;
                $user->save();

                dispatch(new SaveUserAvatar($user));
            }

            try {
                if (!$token = JWTAuth::fromUser($user)) {
                    return response()->json(['code' => 9000, 'msg' => 'invalid_credentials']);
                }
            } catch (JWTException $e) {
                return response()->json(['code' => 9000, 'msg' => 'could_not_create_token']);
            }

            $data = ['token' => $token];
            foreach (['avatar', 'nickname'] as $key) {
                $data[$key] = $user->{$key};
            }

            return response()->json(['code' => 1000, 'data' => $data]);
        }

    }

    public function mobile(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'mobile' => 'required',
            'password' => 'required',
        ]);

        if ($validator->fails()) {
            return response()->json(['code' => 9000, 'msg' => $validator->errors()->first()]);
        }

        $numbers = array(1 => '13012345677');

        $mobile = $request->input('mobile');
        $password = $request->input('password');
        if (!(in_array($mobile, $numbers) && $password == '123456')) {
            return response()->json(['code' => 9000, 'msg' => 'invalid_mobile_or_password']);
        }

        $user = User::find(array_search($mobile, $numbers));
        $token = JWTAuth::fromUser($user);

        $data = ['token' => $token];
        foreach (['avatar', 'nickname'] as $key) {
            $data[$key] = $user->{$key};
        }

        return response()->json(['code' => 1000, 'data' => $data]);
    }
}